<?php
namespace app\controller;

use think\Request;
use think\Response;
use think\facade\Db;

class DepartmentManagement
{
    /**
     * 获取部门列表
     */
    public function getList(Request $request)
    {
        $params = $request->param();
        
        // 直接使用无前缀表名
        $query = Db::name('user_department');

        // 条件筛选
        if (!empty($params['label'])) {
            $query->whereLike('name', '%'.$params['label'].'%');
        }

        // 分页查询
        $list = $query->paginate([
            'page' => $params['pageNo'] ?? 1,
            'list_rows' => $params['pageSize'] ?? 20,
            'query' => $params
        ]);

        return json([
            'code' => 200,
            'data' => [
                'list' => $list->items(),
                'total' => $list->total()
            ]
        ]);
    }

    /**
     * 新增/编辑部门
     */
public function doEdit(Request $request)
{
    $data = $request->post();
    
    try {
        // 基础验证
        if (empty($data['name']) || empty($data['code'])) {
            throw new \Exception('部门名称和权限标识不能为空');
        }

        // 检查部门名称是否重复
        $nameExists = Db::name('user_department')
            ->where('name', $data['name'])
            ->when(!empty($data['id']), function($query) use ($data) {
                $query->where('id', '<>', $data['id']);
            })
            ->count() > 0;
            
        if ($nameExists) {
            throw new \Exception('部门名称已存在');
        }

        // 检查权限标识码是否重复
        $codeExists = Db::name('user_department')
            ->where('code', $data['code'])
            ->when(!empty($data['id']), function($query) use ($data) {
                $query->where('id', '<>', $data['id']);
            })
            ->count() > 0;
            
        if ($codeExists) {
            throw new \Exception('权限标识码已存在');
        }

        // 处理数据
        $saveData = [
            'name' => $data['name'],
            'code' => $data['code'],
            'create_time' => date('Y-m-d H:i:s')
        ];

        // 新增或更新
        if (empty($data['id'])) {
            $result = Db::name('user_department')->insert($saveData);
            $action = '新增';
        } else {
            $result = Db::name('user_department')
                ->where('id', $data['id'])
                ->update($saveData);
            $action = '更新';
        }

        return json([
            'code' => 200,
            'message' => $action.'成功'
        ]);

    } catch (\Exception $e) {
        return json([
            'code' => 500,
            'message' => $e->getMessage()
        ], 500);
    }
}

    /**
     * 删除部门（物理删除）
     */
    public function doDelete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            // 物理删除
            $result = Db::name('user_department')
                ->where('id', $id)
                ->delete();

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '删除成功'
                ]);
            }

            throw new \Exception('删除失败，记录不存在');

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}